﻿using System;
using System.Collections.Generic;

namespace HouseKeeperCore.Elemental
{
    /// <summary>
    ///  A class that manages the ID designation by tracking all the IDs 
    ///  that have been assigned for a group of ID users.
    ///  This implementation is not optimal in the sense that linear search is used for finding the first hole
    /// </summary>
    public class IdGenerator
    {
        #region Properties

        /// <summary>
        ///  All IDs that have been assigned
        /// </summary>
        private readonly ISet<long> _usedIds = new HashSet<long>();

        #endregion

        #region Methods

        /// <summary>
        ///  Gets an unused ID
        /// </summary>
        /// <returns>An unused ID</returns>
        public long Assign()
        {
            long id = 1;

            // TODO optimise it
            for (; _usedIds.Contains(id); id++)
            {
            }

            return id;
        }

        /// <summary>
        ///  Puts an ID back into the store after use
        /// </summary>
        /// <param name="id">The ID to unassign</param>
        public void Unassign(long id)
        {
            if (!_usedIds.Contains(id))
            {
                throw new HouseKeeperException(
                    String.Format("Id {0} that hasn't been assigned cannot be unassigned", id));
            }

            _usedIds.Remove(id);
        }

        #endregion
    }
}
